package com.yoomiito.app.ui.order.sureorder.shopcar;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.yoomiito.app.R;
import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.base.BaseActPresenter;
import com.yoomiito.app.model.bean.AddressInfo;
import com.yoomiito.app.model.my.MyRemainMoneyInfo;
import com.yoomiito.app.model.order.CreateOrderInfo;
import com.yoomiito.app.model.order.PayResultInfo;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.pay.PayTypeUtils;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.YMToast;

import org.reactivestreams.Publisher;

import java.util.LinkedHashMap;

import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.BaseModel;
import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.functions.Function;
import okhttp3.RequestBody;

public class ShopCarBuyGoodsPresenter extends BaseActPresenter<ShopCarBuyGoodsActivity> {

    public ShopCarBuyGoodsPresenter(AppConfig appConfig) {
        super(appConfig);
    }

    public void createOrder(String json, String consignee, String provinceId,
                            String cityId, String countryId, String areaName, String tel, String address) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("json", json);
        params.put("consignee", consignee);
        params.put("area_id", provinceId);
        params.put("area_id2", cityId);
        params.put("area_id3", countryId);
        params.put("area_name", areaName);
        params.put("mobile", tel);
        params.put("address", address);
        RequestBody body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params));
        YmApi.getYmService()
                .createOrderFromShopCar(body)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .flatMap((Function<CreateOrderInfo, Publisher<BaseModel<MyRemainMoneyInfo>>>) str -> {
                    if (hasV()) {
                        getV().mPayOrderId = str.getId();
                        getV().mPayMoney = str.getAmount_paid();
                        getV().mCreateOrderInfo = str;
                        getV().createOrderSuccess();
                    }
                    return YmApi.getYmService().getMoneyAgent();
                })
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<MyRemainMoneyInfo>(handleException()) {
                    @Override
                    public void onSuccess(MyRemainMoneyInfo data) {
                        if (hasV()) {
                            getV().dismissLoading();
                            getV().showPayDialog(data);
//                        getV().orderId = orderResult.getOut_trade_no();
//                        PayTypeUtils.wxPay(orderResult);
                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        if (hasV())
                            getV().dismissLoading();
                    }
                });
    }

    public void pay(String id, int wx, int ali, String account, int orderType, String psw) {
        YmApi.getYmService()
                .multipPay(id, wx, ali, account, orderType, psw, "0")
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<PayResultInfo>() {
                    @Override
                    public void onSuccess(PayResultInfo payResultInfo) {
                        if (getV()==null)return;
                        if ("accountpay".equals(payResultInfo.getPay_type())) {
                            EventMessage eventMessage = new EventMessage();
                            eventMessage.setCode(AllCode.Success);
                            getV().payResult(eventMessage);
                        } else {
                            getV().dismissLoading();
                            getV().mQueryOrderID = payResultInfo.getOut_trade_no();
                            getV().pay_type = payResultInfo.getPay_type();
                            if ("wxpay".equals(payResultInfo.getPay_type())) {
                                PayTypeUtils.wxPay(payResultInfo.getData());
                            } else {
                                PayTypeUtils.aliPay(getV(), payResultInfo.getData().getAlipay_order());
                            }

                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        YMToast.showText(error.getMsg());
                        if (getV()==null)return;
                        getV().dismissLoading();
                        if (error.getCode() == ApiException.PAY_PSW_ERROR) {
                            getV().error(true, ResUtil.getString(R.string.psw_error));
                        } else if (error.getCode() == ApiException.BALANCE_INSUFFICIENT) {
                            getV().error(ResUtil.getString(R.string.balance_poor));
                        } else {
                            getV().error(false, "");
                            EventMessage eventMessage = new EventMessage();
                            eventMessage.setCode(AllCode.Fail);
                            getV().payResult(eventMessage);
                        }
                    }
                });
    }

    //获取当前余额
    public void getIsAgent() {
        YmApi.getYmService()
                .getMoneyAgent()
                .compose(getV().bindToLifecycle())
                .compose(XApi.<MyRemainMoneyInfo>getApiTransformerData())
                .compose(XApi.<MyRemainMoneyInfo>getScheduler())
                .subscribe(new ApiSubscriber<MyRemainMoneyInfo>() {
                    @Override
                    public void onSuccess(MyRemainMoneyInfo data) {

                    }

                    @Override
                    public void onFail(ApiException error) {
                        YMToast.showText(error.getMsg());
                    }
                });
    }

    public void queryOrder(String orderId, String pay_type) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        EventMessage eventMessage = new EventMessage();
        YmApi.getYmService()
                .quseryOrderStatus(orderId, pay_type)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>(handleException()) {
                    @Override
                    public void onSuccess(BaseModel baseModel) {
                        if (hasV()){
                            eventMessage.setCode(AllCode.Success);
                            getV().payResult(eventMessage);
                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        if (hasV()){
                            eventMessage.setCode(AllCode.Fail);
                            getV().payResult(eventMessage);
                        }
                    }
                });
    }

    public void getAddress(){
        YmApi.getYmService()
                .getDefaultAddress()
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<AddressInfo>() {
                    @Override
                    public void onSuccess(AddressInfo addressInfo) {
//                        if (addressInfos.size()==0){
                        getV().showAddressView(addressInfo);
//                        }else {
//                            for (AddressInfo addressInfo:addressInfos) {
//                                if ("1".equals(addressInfo.getIsDefault())){
//                                    getV().showAddressView(addressInfo);
//                                }
//                            }
//                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        if (!TextUtils.isEmpty(error.getMsg())){
                            YMToast.showText(error.getMsg());
                        }
                    }
                });
    }


}
